
#
# This module allows pymak files to access data that is in the comonents XML
# file that is normally in the top-level directory of the component.
#

# Python imports
import sys
import os
import traceback
import logging
from xml.dom.minidom import parse


# Package imports
import variant

def get_variants_from_component_file(comp_file_name, exclude = []):
    result = []
    try:
        root = parse(comp_file_name)
        variants_root = root.getElementsByTagName("variants")[0]
        variants = variants_root.getElementsByTagName("variant")
        for v in variants:
            name = v.getAttribute("name")
            if name in exclude:
                continue
            values = v.getAttribute("value")
            if values:
                values = values[2:-1]
                values = values.split("|")
                values = [ str(x) for x in values ]
            else:
                values = []
                for val in v.getElementsByTagName("value"):
                    data = str(val.childNodes[0].data)
                    def_attr = val.getAttribute("default")
                    if def_attr and def_attr.lower() == "true":
                        values.insert(0, data)
                    else:
                        values.append(data)

            name = str(name)
            result.append(variant.new_variant_value(name, values, values[0]))

    except Exception, e:
        logging.error("Failed to read in component file %s to get variant values." % comp_file_name)
        print sys.exc_info()
        traceback.print_exc(sys.exc_info()[2])
        sys.exit(1)

    return result


